# -*- coding: utf-8 -*-
"""
Coroutines and concurrency/Tornado Gen/test02.py
"""
import time
import asyncio
import tornado.web
import random
from datetime import timedelta
from tornado import gen
from tornado.httpclient import AsyncHTTPClient


class IndexHandler(tornado.web.RequestHandler):

    def get(self):
        i_flag = gen.is_coroutine_function(self.get_process)
        r_message = f"put_process is coroutine function: {i_flag}"

        gen.multi([
            self.get_process("http://www.baidu.com"),
            self.get_process("http://www.google.com"),
        ])
        gen.multi_future([
            self.get_process("http://www.baidu.com"),
            self.get_process("http://www.google.com"),
        ])
        self.finish(f"I'm back.{r_message}")

    @gen.coroutine
    def get_process(self, url):
        task_id = random.randint(0, 5)
        print(f"Task id {task_id} start. {time.time()}")
        response = yield gen.with_timeout(timedelta(seconds=2), self.get_task(url))
        print(response)
        print(f"Task id {task_id} end. {time.time()}")

    @gen.coroutine
    def get_task(self, url):
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(url)

        raise gen.Return(response)


async def main():
    app = tornado.web.Application([
        (r"/", IndexHandler)
    ])
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(main())
